import sun.misc.PostVMInitHook;

import java.security.PublicKey;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-10-24
 * Time: 19:55
 */
public class MyBlockingQueue {
    //利用数组实现循环队列
    private int[] queue=new int[1000];
    private int usedSize;//记录队列中元素个数,用来区分满还是空
    private int head;
    private  int tail;
    private Object locker=new Object();


    //放数据
    public void put(int val) throws InterruptedException {
        //保证线程安全
        synchronized(this.locker){
            //判断是否满
            if(this.usedSize==queue.length){
                //满了就阻塞
                this.locker.wait();//注意对那个对象上锁就是那个对象wait
            }
            this.queue[tail]=val;
            this.tail++;
            if(tail==queue.length){
                tail=0;//相比于tail%(queue.length)来说更直观并且效率更高
            }
            this.usedSize++;
            //成功添加就notify
            this.locker.notify();//注意放到锁内,不然出现illegalMonitorStateException
        }
    }

    //取数据
    public Integer take() throws InterruptedException {
        synchronized(this.locker){
            if(this.usedSize==0){
                this.locker.wait();
            }
            int ret=this.queue[head];
            head++;
            if(head==this.queue.length){
                this.head=0;
            }
            this.usedSize--;
            this.locker.notify();
            return ret;
        }
    }

  public static void main(String[] args) {
    MyBlockingQueue queue=new MyBlockingQueue();
      Thread producer=new Thread(()->{
          int num=1;
          while(true){
              try {
                  queue.put(num);
                  System.out.println("生产者生产了一个"+num);
                  num++;

              } catch (InterruptedException e) {
                  throw new RuntimeException(e);
              }
          }
      });
      producer.start();
      Thread customer=new Thread(()->{
          while(true){
              try {
                  int ret=queue.take();
                  Thread.sleep(1000);
                  System.out.println("消费者消费了一个"+ret);
              } catch (InterruptedException e) {
                  throw new RuntimeException(e);
              }
          }
      });
      customer.start();
  }
}
